import logging
import time


class LogInfo:

    def __init__(self,name='V&V'):
        # 初始化logger对象
        self.logger = logging.getLogger(name)

    def set_message(self,level,msg):
        global fh, ch
        try:
            # 创建时间
            now = time.strftime('%Y-%m-%d')
            # 创建文件句柄
            fh = logging.FileHandler('../../Log/auto_' + now + '.log')
            # 控制台输出流
            ch = logging.StreamHandler()
            # 格式化输出
            fm = logging.Formatter('%(name)s-%(asctime)s-%(levelname)s-%(message)s')
            # 文件设置格式
            fh.setFormatter(fm)
            # 控制台输出设置格式
            ch.setFormatter(fm)
            # 文件句柄加入logger对象
            self.logger.addHandler(fh)
            # 控制台句柄加入logger
            self.logger.addHandler(ch)
            # 设置打印级别
            self.logger.setLevel(logging.DEBUG)
            if level.lower() == 'debug':
                self.logger.debug(msg)
            elif level.lower() == 'info':
                self.logger.info(msg)
            elif level.lower() == 'warning':
                self.logger.warning(msg)
            elif level.lower() == 'error':
                self.logger.error(msg,exc_info=True,stack_info=True)
                #,exc_info=True,stack_info=True
            elif level.lower() == 'critical':
                self.logger.critical(msg,exc_info=True,stack_info=True)
            else:
                print('logger level error!')
            # 移除控制台对象
            self.logger.removeHandler(ch)
            # 移除文件对象
            self.logger.removeHandler(fh)
        except Exception as e:
            print(e, 'logger operation error~')
        finally:
            fh.close()
            ch.close()
